package com.uniknow.app.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import roboguice.inject.InjectView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uniknow.app.AppConfig;
import com.uniknow.app.AppContext;
import com.uniknow.app.R;
import com.uniknow.app.bin.NewsBean;
import com.uniknow.app.bin.NewsItemBean;
import com.uniknow.app.bin.UniChannelBean;
import com.uniknow.app.operate.BaseListener;
import com.uniknow.app.operate.CommonOperate;
import com.uniknow.app.operate.HttpPath;
import com.uniknow.app.operate.impl.CommonOperateImpl;
import com.uniknow.app.util.FileUtils;
import com.uniknow.app.util.ImageUtils;
import com.uniknow.app.util.StringUtils;
import com.uniknow.app.util.Sysout;
import com.uniknow.app.util.UIHelper;
import com.uniknow.app.util.UploadUtil;

public class NewsPublishActivity extends BaseActivity implements OnClickListener{
	/**
	 * 相册
	 */
	private Context mContext;
	private static final int RESULT_GET_CAMERA = 0;
	private static final int RESULT_LOAD_IMAGE = 1;
	private LayoutInflater listImgItem;//视图容器
	private CommonOperate operate;
	private Dialog choseImage;
	private int choosepos = 0;
	private String realImgPath,realVoicePath;
	
	@InjectView(R.id.header_btn_center)
	private TextView title;
	@InjectView(R.id.header_btn_left)
	private TextView titleLeftBtn;
	@InjectView(R.id.header_btn_right)
	private TextView titleRightBtn;
	@InjectView(R.id.newspublish_title)
	private EditText newsTitle;
	@InjectView(R.id.newspublish_context)
	private EditText newsContext;
	@InjectView(R.id.activity_newspublish_panel)
	private LinearLayout itemPanel;
	@InjectView(R.id.activity_newspublish_add)
	private Button addBtn;
	@InjectView(R.id.activity_newspublish_chose)
	private Button choseBtn;
	@InjectView(R.id.activity_newspublish_send)
	private Button sendBtn;
	private List<ListItemView> listItems = new ArrayList<ListItemView>();
	private NewsBean newsBean = new NewsBean();
	private List<NewsItemBean> listNewsItems = new ArrayList<NewsItemBean>();
	
	static class ListItemView{//自定义控件集合  
		public ImageView img;
        public TextView del;
        public TextView dsc;
	}
	
	@SuppressLint("HandlerLeak")
	private  Handler mhandler = new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
		
			switch (msg.what) {
			case RESULT_LOAD_IMAGE:
				UIHelper.show(mContext, "获相册的图像");
				loadImage(msg.obj.toString());
				break;
			default:
				break;
			}
			
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newspublish);
		mContext = this;
		listImgItem = LayoutInflater.from(mContext);
		operate = CommonOperateImpl.getOperate(mContext);
		initView();
	}
	
	public void initView(){
		addBtn.setOnClickListener(this);
		choseBtn.setOnClickListener(this);
		sendBtn.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn.setText("发布");
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_newspublish_add:
			UIHelper.show(mContext, "add");
			showImagePick();
			break;
		case R.id.activity_newspublish_chose:
					
			break;
		case R.id.activity_newspublish_send:
			send();
			break;
		case R.id.header_btn_right:
			send();
			break;
		}
	}
	
	/**
	 * 方法名：showImagePick
	 * 描述：相册选择图片
	 * @参数：   参数名  参数类型   参数描述
	 * @返回值类型： void   
	 * @创建时间：  2014年11月5日 
	 * @创建者：韩创
	 * @变更记录：2014年11月5日下午6:19:19 by
	 */
	public void showImagePick(){
		//弹出选择对话框
		if(null == choseImage){
			final String[] items = {"相册选取","手机拍照","纯文字描述","添加封面"};
			choseImage = new AlertDialog.Builder(this)
			.setTitle("请选择元素类型")  
		    .setSingleChoiceItems(items, choosepos,   
		      new DialogInterface.OnClickListener() {  
		                                  
		         public void onClick(DialogInterface dialog, int which) {  
		            dialog.dismiss();  
		            choosepos = which;
		            switch (which) {
					case 0:
						Intent intent = new Intent(Intent.ACTION_PICK, null);
						intent.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
						NewsPublishActivity.this.startActivityForResult(intent, RESULT_LOAD_IMAGE);
						break;
					case 1:
						if (FileUtils.checkSaveLocationExists()) { // 检测sd是否可用  
		                    System.out.println("SD card is not avaiable/writeable right now.");
		                    UIHelper.ToastMessage(AppContext.getInstance(),getResources().getString(R.string.SD_card_not_avaiable));
		                    return;  
		                }
						realImgPath = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
						realImgPath = FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+realImgPath;
						System.out.println("realImgPath = "+realImgPath);
		                FileUtils.creatSDDir(AppConfig.FOLDER_IMG);
		                Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(realImgPath)));//直接保存到本地磁盘上，确保图片分辨率和清晰度
		                //TODO 拍照大小为默认屏幕大小 android.media.action.IMAGE_CAPTURE
		                //Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
		                //getImageByCamera.setAction(Intent.ACTION_GET_CONTENT);
	                    //startActivityForResult(intent, 1);
		                startActivityForResult(getImageByCamera, RESULT_GET_CAMERA);
						break;
					case 2:
						break;
					case 3:
						break;
					}
		           
		         }  
		      }  
		    )  
		    .setNegativeButton("取消", null)  
		    .show();
		}else{
			choseImage.show();
		}
	}
	
	public void loadImage(final String path){
		Sysout.i("path = "+path);
		final View convertView = listImgItem.inflate(R.layout.item_news_add, null);
		ListItemView  listItemView = new ListItemView();
		listItemView.img = (ImageView) convertView.findViewById(R.id.item_news_img);
		listItemView.del = (TextView) convertView.findViewById(R.id.item_news_img_del);
		listItemView.dsc = (TextView) convertView.findViewById(R.id.item_news_img_dsc);
		listItemView.img.setImageBitmap(ImageUtils.decodeHeadIconFile(path));
		listItemView.img.setTag(path);
		itemPanel.addView(convertView);
		listItemView.del.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				itemPanel.removeView(convertView);
				
			}
		});
		listItems.add(listItemView);
	}
	/**
	 * 发送消息
	 */
	@SuppressLint("HandlerLeak")
	Handler handlerUploadImage = new Handler() {

		  public void handleMessage(Message message) {
			  if (message.obj=="success") {
				  if(listNewsItems.size()>0){
					  newsBean.setNewsItems(listNewsItems);
					  newsBean.setImg(listNewsItems.get(0).getPath()); 
				  }
				  /*operate.sendNews(AppContext.user, newsBean, new BaseListener() {
					
					@Override
					public void onSuccess(Object o) {
						closeLoading();
						UIHelper.show(mContext, "发送成功！");
						finish();
					}
					
					@Override
					public void onError(String e) {
						closeLoading();
						UIHelper.show(mContext, "发送失败！"+e);
					}
				});*/
				//TODO 测试附带选择渠道
				List<UniChannelBean> listChannel = new ArrayList<UniChannelBean>();
				UniChannelBean c1 = new UniChannelBean();
				c1.setChannelType(UniChannelBean.channelTypeUni);
				UniChannelBean c2 = new UniChannelBean();
				c2.setChannelType(UniChannelBean.channelTypeWix);
				c2.setId(3);
				listChannel.add(c1);
				listChannel.add(c2);
				
				operate.publicNews(AppContext.user, newsBean,listChannel, new BaseListener() {
						
						@Override
						public void onSuccess(Object o) {
							closeLoading();
							UIHelper.show(mContext, "发送成功！");
							finish();
						}
						
						@Override
						public void onError(String e) {
							closeLoading();
							UIHelper.show(mContext, "发送失败！"+e);
						}
					});
				  
			  }else{
				  closeLoading();
			  }
			  
		  }
	 };
	/**
	 * 发送信息
	 */
	public void send(){
		if(!checkNewsData())return;
		showLoading();
		newsBean.setTitle(newsTitle.getText().toString());
		newsBean.setText(newsContext.getText().toString());
		new Thread(new Runnable() {
			@Override
			public void run()
			{
				String return_str = "success";
				//循环上传图片
				uploadImages();
				Message msg_listData = new Message();
				msg_listData.obj = return_str;
				handlerUploadImage.sendMessage(msg_listData);
			}
		}).start();
		
	}
	/**
	 * 检测数据合法性
	 * @return
	 */
	public boolean checkNewsData(){
		if(StringUtils.isEmpty(newsTitle)){
			UIHelper.show(mContext, "标题不能为空！");
			return false;
		}
		if(StringUtils.isEmpty(newsContext)){
			UIHelper.show(mContext, "内容不能为空！");
			return false;
		}
		return true;
	}
	/**
	 * 上传图片
	 */
	public void uploadImages(){
		for(ListItemView item:listItems){
			NewsItemBean newsItemBean = new NewsItemBean();
			String str = UploadUtil.uploadFile(mContext,item.img.getTag().toString(), HttpPath.WEB_UPLOAD, HttpPath.WEB_UPLOAD);
			Sysout.i(NewsPublishActivity.class,"upload str = "+str);
			int id = Integer.parseInt(str.split(",")[0]);
			newsItemBean.setUserid(AppContext.user.getUserid());
			newsItemBean.setFileid(id);
			newsItemBean.setPath(str.split(",")[1]);
			newsItemBean.setText(item.dsc.getText().toString());
			listNewsItems.add(newsItemBean);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == Activity.RESULT_OK){
			switch(requestCode){
			case RESULT_LOAD_IMAGE:
    	        Uri selectedImage = data.getData();
    	        String[] filePathColumn = { MediaStore.Images.Media.DATA };

    	        Cursor cursor = mContext.getContentResolver().query(selectedImage,
    	                filePathColumn, null, null, null);
    	        cursor.moveToFirst();

    	        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    	        String picturePath = cursor.getString(columnIndex);
    	        cursor.close();			
				
				if(mhandler != null){
					Message msg = mhandler.obtainMessage();
					msg.what = RESULT_LOAD_IMAGE;
					msg.obj = picturePath;
					mhandler.sendMessage(msg);	
				}
				break;
			case RESULT_GET_CAMERA:
				if (requestCode == RESULT_GET_CAMERA && resultCode == RESULT_OK) {
					if(mhandler != null){
						Message msg = mhandler.obtainMessage();
						msg.what = RESULT_LOAD_IMAGE;
						msg.obj = realImgPath;
						mhandler.sendMessage(msg);	
					}
				}
				break;
			}
		}
		
	}
	

}
